import cv2
import numpy as np

def compare_images(image1, image2):

    # 初始化ORB检测器
    orb = cv2.ORB_create()

    # 找到关键点和描述符
    kp1, des1 = orb.detectAndCompute(image1, None)
    kp2, des2 = orb.detectAndCompute(image2, None)

    # 创建BFMatcher对象
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

    # 进行匹配
    matches = bf.match(des1, des2)

    # 根据匹配距离进行排序
    matches = sorted(matches, key=lambda x: x.distance)

    # 计算匹配的特征点的比例
    num_matches = len(matches)
    num_features = max(len(des1), len(des2))

     # 安全检查以防一张图片没有特征点
    if num_features == 0:
        return 0.0
    
    # 相似度是匹配特征点数除以最大特征点数
    similarity = num_matches / num_features
    
    return similarity
